package alibaba.threadlocal.demo01;

import lombok.extern.slf4j.Slf4j;

/**
 * @author ChangLiang
 * @date 2020/4/20
 */
@Slf4j
public class UserContext implements AutoCloseable {

    /**
     * 在这个类似User上下文的类里面 把User放进去 这样在这个线程中就共享这个变量了
     */
    static final ThreadLocal<User> THREAD_LOCAL_CONTEXT = new ThreadLocal<>();

    public UserContext(User user) {
        THREAD_LOCAL_CONTEXT.set(user);
    }

    public static User getCurrentUser() {
        return THREAD_LOCAL_CONTEXT.get();
    }

    @Override
    public void close() {
        log.info(Thread.currentThread().getName()+" close");
        THREAD_LOCAL_CONTEXT.remove();
    }
}
